<template>
    <el-card>
        <el-form label-width="70px">
            <el-row :gutter="10">
                <el-col :span="6">
                    <el-form-item label="课程名称">
                        <el-select v-model="courseId" placeholder="请选择课程" @change="clearCharData">
                            <el-option v-for="item in courseList" :key="item.id" :label="item.name" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="3">
                    <el-button type="primary" @click="searchGrade"> 统计分析</el-button>
                </el-col>
            </el-row>
        </el-form>
    </el-card>
    <EchartsComponent :chart-data="charData" v-if="dialogVisible"/>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import EchartsComponent from "@/components/Grade/EchartsComponent.vue";
import {FindAllCourse} from "@/api/course";
import {GetCharData} from "@/api/grade";
import {ElMessage} from "element-plus";

const dialogVisible = ref(false)
const courseId = ref('');
const courseList = ref([])
const charData = ref({
    category: [],
    averageData: [],
    maxData: [],
    minData: [],
    failData: [],
});
const clearCharData = () => {
    charData.value = {};
    dialogVisible.value = false;
};
const searchGrade = async () => {
    if (!courseId.value) {
        round(4)
    }else {
        const {data, code} = await GetCharData(courseId.value);
        if (code !== 200) {
            ElMessage.error('获取数据失败');
            return;
        }
        charData.value = {
            category: data.category,
            averageData: data.averageData,
            maxData: data.maxData,
            minData: data.minData,
            failData: data.failData,
        };
    }
    dialogVisible.value = true;
}

onMounted(async () => {
    const {data} = await FindAllCourse();
    courseList.value = data
})

const round = (num) => {
    // 生成指定数量年级（例如6个）
    const years = Array.from({length: num}, (_, i) => 2019 + i + '级');
    const randomBetween = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
    const generateRandomData = length => Array.from({length}, () => randomBetween(30, 80));
    charData.value = {
        category: years,
        averageData: generateRandomData(num),
        maxData: generateRandomData(num),
        minData: generateRandomData(num).map(val => Math.max(val - 20, 0)), // 确保最低分不高于平均分
        failData: generateRandomData(num).map(val => Math.floor(Math.random() * 6)) // 随机生成0-5之间的不及格人数
    };
}
</script>
